package com.example.application.views.pet;

import com.example.application.bean.*;
import com.example.application.views.util.MapToJsonUtil;
import com.example.application.views.util.MyHttpClientUtil;
import com.example.application.views.util.DialogUtil;
import com.example.application.views.util.VerifyUtil;
import com.example.page.PageComponent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.converter.StringToIntegerConverter;
import com.vaadin.flow.data.renderer.TemplateRenderer;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.PageTitle;
import com.example.application.views.main.MainView;
import com.vaadin.flow.component.dependency.CssImport;

import java.util.HashMap;
import java.util.Map;

@Route(value = "pets", layout = MainView.class)
@PageTitle("宠主管理")
@CssImport("./views/宠物管理/宠物管理-view.css")
public class PetView extends Div {

    private Grid<PetOwner> grid = new Grid<>(PetOwner.class, false);
    private Crud<PetOwner> crud = new Crud<>(PetOwner.class, grid, createPetOwnerEditor());

    private ObjectMapper mapper = new ObjectMapper();

    private PageBean<PetOwner> pageBean = null;
    //当前页数
    private int curPage = 1;
    //每页显示条数
    private int pageSize = 5;
    //总条数
    private int tolNum;
    //总页数
    private int tolPage;

    private Map<String,Object> condition = new HashMap<>();


    private PetOwner petOwner;

    private TextField petOwnerPic;
    private TextField nickname;
    private TextField realName;
    private TextField telNum;
    private TextField vipNum;
    private TextField address;
    private TextField region;
    private TextField integral;
    private TextField petName;

    public PetView(){
        User user = (User) UI.getCurrent().getSession().getAttribute("user");
        if (user == null){

        }else if("平台管理员".equals(user.getIdentity())){
            this.init();
        }else{
            DialogUtil.adminAuthority();
        }
    }

    private void createGridLayout(SplitLayout splitLayout) {
        Div wrapper = new Div();
        wrapper.setId("grid-wrapper");
        wrapper.setWidthFull();

        PageComponent pageComponent = new PageComponent(
                curPage,pageSize,tolNum,tolPage) {
            //下一页
            @Override
            protected void pageNext() {
                PetView.this.curPage = curPage;
                updateForm();
            }

            //上一页
            @Override
            protected void pagePrevious() {
                PetView.this.curPage = curPage;
                updateForm();
            }

            @Override
            protected void gotoPage() {
                PetView.this.curPage = curPage;
                updateForm();
            }

            @Override
            protected void firstPage() {
                PetView.this.curPage = 1;
                updateForm();
            }

            @Override
            protected void lastPage() {
                PetView.this.curPage = tolPage;
                updateForm();
            }

            @Override
            protected void selectPage() {
                PetView.this.pageSize = pageSize;
                updateForm();
            }
        };
        pageComponent.components.add(crud);
        pageComponent.init();
        splitLayout.addToPrimary(pageComponent);
    }

    private CrudEditor<PetOwner> createPetOwnerEditor() {
        petOwnerPic = new TextField("头像");
        nickname = new TextField("昵称");
        realName = new TextField("姓名");
        telNum = new TextField("电话");
        vipNum = new TextField("会员号");
        address = new TextField("地址");
        region = new TextField("地区");
        integral = new TextField("积分");
        petName = new TextField("宠物名");
        FormLayout form = new FormLayout(nickname, realName, telNum, vipNum, address, region, integral, petName);

        Binder<PetOwner> binder = new Binder<>(PetOwner.class);
        binder.bind(petOwnerPic,PetOwner::getPic,PetOwner::setPic);
        binder.bind(nickname, PetOwner::getNickname, PetOwner::setNickname);
        binder.bind(realName, PetOwner::getRealName, PetOwner::setRealName);
        binder.bind(telNum, PetOwner::getTelNum, PetOwner::setTelNum);
        binder.bind(vipNum, PetOwner::getVipNum, PetOwner::setVipNum);
        binder.bind(address, PetOwner::getAddress, PetOwner::setAddress);
        binder.bind(region, PetOwner::getRegion, PetOwner::setRegion);
        binder.forField(integral).withConverter(new StringToIntegerConverter("请输入数字")).bind(PetOwner::getIntegral, PetOwner::setIntegral);
        binder.bind(petName, PetOwner::getPetName, PetOwner::setPetName);

        return new BinderCrudEditor<>(binder, form);
    }




    public void init(){

        SplitLayout splitLayout = new SplitLayout();
        splitLayout.setSizeFull();
        updateForm();

        createGridLayout(splitLayout);

        Crud.addEditColumn(grid);
        grid.addColumn(TemplateRenderer.<PetOwner>
                of("<img src=[[item.photoSource]] style=\"height: 40px; border-radius: 50%;\">")
                .withProperty("photo", PetOwner::getPic))
                .setHeader("头像")
                .setFlexGrow(0);
        // grid.addColumn(PetOwner::getPic).setHeader("头像");
        grid.addColumn(PetOwner::getNickname).setHeader("昵称");
        grid.addColumn(PetOwner::getRealName).setHeader("姓名");
        grid.addColumn(PetOwner::getTelNum).setHeader("电话");
        grid.addColumn(PetOwner::getVipNum).setHeader("会员号");
        grid.addColumn(PetOwner::getAddress).setHeader("地址");
        grid.addColumn(PetOwner::getRegion).setHeader("地区");
        grid.addColumn(PetOwner::getIntegral).setHeader("积分");
        grid.addColumn(PetOwner::getPetName).setHeader("宠物名");
        grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);
        grid.setHeightFull();

        add(crud);
        add(splitLayout);



        // 添加和修改
        crud.addSaveListener(e -> {
            petOwner = e.getItem();
            Integer id = petOwner.getId();

            petOwner.setPic(petOwnerPic.getValue());
            petOwner.setNickname(nickname.getValue().trim());
            petOwner.setRealName(realName.getValue().trim());
            petOwner.setTelNum(telNum.getValue().trim());
            petOwner.setVipNum(vipNum.getValue().trim());
            petOwner.setAddress(address.getValue().trim());
            petOwner.setRegion(region.getValue().trim());
            petOwner.setIntegral(Integer.parseInt(integral.getValue()));
            petOwner.setPetName(petName.getValue().trim());

            // 添加
            if(id == null){
                // System.out.println("添加");
                if(this.verifyInfo(petOwner)){
                    System.out.println("222222222");
                    try {
                        String msg = MyHttpClientUtil.httpPost(PetUrl.PET_ADD, petOwner, "utf-8");

                        JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, PetOwner.class);
                        ResultBean<PetOwner> petOwnerResultBean = mapper.readValue(msg,javaType);

                        if (petOwnerResultBean.getCode() == 0){
                            UI.getCurrent().getPage().executeJs("alert('添加失败')");
                        }else{
                            updateForm();
                        }
                    }catch (Exception e1){
                        e1.printStackTrace();
                    }
                }

                // 修改
            }else if (id != null){
//                System.out.println("修改 id为：" + petOwner.getId());
                if(this.verifyInfo(petOwner)){
                    System.out.println("11111111111");
                    try {
                        String msg = MyHttpClientUtil.httpPut(PetUrl.PET_UPDATE, petOwner, "utf-8");
                        JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, PetOwner.class);
                        ResultBean<PetOwner> petOwnerResultBean = mapper.readValue(msg,javaType);

                        if (petOwnerResultBean.getCode() == 0){
                            UI.getCurrent().getPage().executeJs("alert('修改失败')");
                        }else{
                            updateForm();
                        }
                    }catch (Exception e1){
                        e1.printStackTrace();
                    }
                }
            }else{
                UI.getCurrent().getPage().executeJs("alert('请先输入数据!')");
            }
            updateForm();
        });

        // 删除
        crud.addDeleteListener(e -> {
            petOwner = e.getItem();
            try {
                if (petOwner.getId() != null){
                    String json = MyHttpClientUtil.httpDelete(PetUrl.PET_DELETE, petOwner.getId(), "utf-8");
                    ResultBean deleteResult = deleteResult = mapper.readValue(json, ResultBean.class);
                    if(deleteResult.getCode() == 1){
                        UI.getCurrent().getPage().executeJs("alert('删除成功');");
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('删除失败');");
                    }
                }else{
                    UI.getCurrent().getPage().executeJs("alert('请先选择一条需要删除的数据');");
                }
            }catch (Exception e1){
                e1.printStackTrace();
            }
            updateForm();
        });

    }

    private void updateForm(){

        String url = PetUrl.SHOW_PETS;
        condition.put("currentPage",PetView.this.curPage);
        condition.put("pageSize",PetView.this.pageSize);
        url= MapToJsonUtil.getUrl(condition,url);
        // System.out.println(url);
        String json = MyHttpClientUtil.HttpGet(url, null);
        // System.out.println(json);

        ObjectMapper objectMapper = new ObjectMapper();
        ResultBean<PageBean<PetOwner>> resultBean=null;

        try {
            resultBean =  objectMapper.readValue(json, new TypeReference<ResultBean<PageBean<PetOwner>>>() { });
            pageBean = resultBean.getT();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        grid.setItems(pageBean.getDatas());

        tolNum = pageBean.getTolNum();
        tolPage = pageBean.getTolPage();
        pageSize = pageBean.getPageSize();
        curPage = pageBean.getCurrentPage();
//        System.out.printf("每页显示条数：%d  总条数：%d  总页数：%d \n",pageSize, tolNum, tolPage);
    }

    public boolean verifyInfo(PetOwner po){
        if(!VerifyUtil.lengthVerify(po.getNickname())){
            UI.getCurrent().getPage().executeJs("alert('昵称长度不能超过10');");
            return false;
        }else if(!VerifyUtil.lengthVerify(po.getRealName())){
            UI.getCurrent().getPage().executeJs("alert('姓名长度不能超过10');");
            return false;
        }else if(!VerifyUtil.telePhoneNumVerify(po.getTelNum())){
            UI.getCurrent().getPage().executeJs("alert('电话号码格式不正确');");
            return false;
        }else if(!VerifyUtil.PointVerify(po.getIntegral()+"")){
            UI.getCurrent().getPage().executeJs("alert('积分不能大于10000');");
            return false;
        }else{
            return true;
        }
    }

}
